import { ipcMain } from 'electron'
import { dbConnection } from '../database/connection'

/**
 * 搜索相关IPC处理
 */
export function setupSearchIpc(): void {
  /**
   * 搜索照片
   */
  ipcMain.handle('search:photos', (_, { query, page = 1, pageSize = 50, filters = {} }) => {
    try {
      const db = dbConnection.getConnection()
      const offset = (page - 1) * pageSize
      
      // 构建搜索条件
      let whereClause = '1=1'
      const params: any[] = []
      
      // 文本搜索（文件名、描述）
      if (query) {
        whereClause += ' AND (file_name LIKE ? OR description LIKE ?)'
        params.push(`%${query}%`, `%${query}%`)
      }
      
      // 日期范围
      if (filters.dateFrom) {
        whereClause += ' AND captured_at >= ?'
        params.push(filters.dateFrom)
      }
      
      if (filters.dateTo) {
        whereClause += ' AND captured_at <= ?'
        params.push(filters.dateTo)
      }
      
      // 相机信息
      if (filters.cameraMake) {
        whereClause += ' AND camera_make = ?'
        params.push(filters.cameraMake)
      }
      
      if (filters.cameraModel) {
        whereClause += ' AND camera_model = ?'
        params.push(filters.cameraModel)
      }
      
      // 评分
      if (filters.rating !== undefined) {
        whereClause += ' AND rating >= ?'
        params.push(filters.rating)
      }
      
      // 标签
      if (filters.tags && filters.tags.length > 0) {
        const tagPlaceholders = filters.tags.map(() => '?').join(',')
        whereClause += ` AND id IN (
          SELECT photo_id FROM photo_tags 
          WHERE tag_id IN (${tagPlaceholders})
          GROUP BY photo_id
          HAVING COUNT(DISTINCT tag_id) = ?
        )`
        params.push(...filters.tags, filters.tags.length)
      }
      
      // 相册
      if (filters.albums && filters.albums.length > 0) {
        const albumPlaceholders = filters.albums.map(() => '?').join(',')
        whereClause += ` AND id IN (
          SELECT photo_id FROM photo_albums 
          WHERE album_id IN (${albumPlaceholders})
        )`
        params.push(...filters.albums)
      }
      
      // 地理位置范围
      if (filters.bounds) {
        const { north, south, east, west } = filters.bounds
        whereClause += ' AND latitude BETWEEN ? AND ? AND longitude BETWEEN ? AND ?'
        params.push(south, north, west, east)
      }
      
      // 获取总数
      const countQuery = `SELECT COUNT(*) as total FROM photos WHERE ${whereClause}`
      const countResult = db.prepare(countQuery).get(...params) as { total: number }
      
      // 获取搜索结果
      const searchQuery = `
        SELECT * FROM photos 
        WHERE ${whereClause}
        ORDER BY captured_at DESC
        LIMIT ? OFFSET ?
      `
      const photos = db.prepare(searchQuery).all(...params, pageSize, offset)
      
      return {
        success: true,
        data: {
          photos,
          pagination: {
            page,
            limit: pageSize,
            total: countResult.total,
            totalPages: Math.ceil(countResult.total / pageSize)
          }
        }
      }
    } catch (error) {
      console.error('搜索照片失败:', error)
      return {
        success: false,
        error: '搜索照片失败'
      }
    }
  })

  /**
   * 搜索相册
   */
  ipcMain.handle('search:albums', (_, { query, page = 1, pageSize = 50 }) => {
    try {
      const db = dbConnection.getConnection()
      const offset = (page - 1) * pageSize
      
      // 构建搜索条件
      let whereClause = '1=1'
      const params: any[] = []
      
      // 文本搜索（相册名称、描述）
      if (query) {
        whereClause += ' AND (name LIKE ? OR description LIKE ?)'
        params.push(`%${query}%`, `%${query}%`)
      }
      
      // 获取总数
      const countQuery = `SELECT COUNT(*) as total FROM albums WHERE ${whereClause}`
      const countResult = db.prepare(countQuery).get(...params) as { total: number }
      
      // 获取搜索结果
      const searchQuery = `
        SELECT a.*, COUNT(pa.photo_id) as photo_count
        FROM albums a
        LEFT JOIN photo_albums pa ON a.id = pa.album_id
        WHERE ${whereClause}
        GROUP BY a.id
        ORDER BY a.updated_at DESC
        LIMIT ? OFFSET ?
      `
      const albums = db.prepare(searchQuery).all(...params, pageSize, offset)
      
      return {
        success: true,
        data: {
          albums,
          pagination: {
            page,
            limit: pageSize,
            total: countResult.total,
            totalPages: Math.ceil(countResult.total / pageSize)
          }
        }
      }
    } catch (error) {
      console.error('搜索相册失败:', error)
      return {
        success: false,
        error: '搜索相册失败'
      }
    }
  })

  /**
   * 搜索标签
   */
  ipcMain.handle('search:tags', (_, { query, page = 1, pageSize = 50 }) => {
    try {
      const db = dbConnection.getConnection()
      const offset = (page - 1) * pageSize
      
      // 构建搜索条件
      let whereClause = '1=1'
      const params: any[] = []
      
      // 文本搜索（标签名称）
      if (query) {
        whereClause += ' AND name LIKE ?'
        params.push(`%${query}%`)
      }
      
      // 获取总数
      const countQuery = `SELECT COUNT(*) as total FROM tags WHERE ${whereClause}`
      const countResult = db.prepare(countQuery).get(...params) as { total: number }
      
      // 获取搜索结果
      const searchQuery = `
        SELECT t.*, COUNT(pt.photo_id) as photo_count
        FROM tags t
        LEFT JOIN photo_tags pt ON t.id = pt.tag_id
        WHERE ${whereClause}
        GROUP BY t.id
        ORDER BY t.name ASC
        LIMIT ? OFFSET ?
      `
      const tags = db.prepare(searchQuery).all(...params, pageSize, offset)
      
      return {
        success: true,
        data: {
          tags,
          pagination: {
            page,
            limit: pageSize,
            total: countResult.total,
            totalPages: Math.ceil(countResult.total / pageSize)
          }
        }
      }
    } catch (error) {
      console.error('搜索标签失败:', error)
      return {
        success: false,
        error: '搜索标签失败'
      }
    }
  })

  /**
   * 获取搜索建议
   */
  ipcMain.handle('search:getSuggestions', (_, { type, query }) => {
    try {
      const db = dbConnection.getConnection()
      let suggestions: any[] = []
      
      switch (type) {
        case 'camera_make':
          suggestions = db.prepare(`
            SELECT DISTINCT camera_make as value, COUNT(*) as count
            FROM photos
            WHERE camera_make LIKE ? AND camera_make IS NOT NULL
            ORDER BY count DESC
            LIMIT 10
          `).all(`%${query}%`)
          break
          
        case 'camera_model':
          suggestions = db.prepare(`
            SELECT DISTINCT camera_model as value, COUNT(*) as count
            FROM photos
            WHERE camera_model LIKE ? AND camera_model IS NOT NULL
            ORDER BY count DESC
            LIMIT 10
          `).all(`%${query}%`)
          break
          
        case 'tags':
          suggestions = db.prepare(`
            SELECT DISTINCT t.name as value, COUNT(pt.photo_id) as count
            FROM tags t
            JOIN photo_tags pt ON t.id = pt.tag_id
            WHERE t.name LIKE ?
            ORDER BY count DESC
            LIMIT 10
          `).all(`%${query}%`)
          break
          
        case 'albums':
          suggestions = db.prepare(`
            SELECT DISTINCT name as value, 
              (SELECT COUNT(*) FROM photo_albums WHERE album_id = a.id) as count
            FROM albums a
            WHERE name LIKE ?
            ORDER BY count DESC
            LIMIT 10
          `).all(`%${query}%`)
          break
      }
      
      return {
        success: true,
        data: suggestions
      }
    } catch (error) {
      console.error('获取搜索建议失败:', error)
      return {
        success: false,
        error: '获取搜索建议失败'
      }
    }
  })

  /**
   * 获取热门标签
   */
  ipcMain.handle('search:getPopularTags', (_, { limit = 20 }) => {
    try {
      const db = dbConnection.getConnection()
      
      const tags = db.prepare(`
        SELECT t.id, t.name, t.color, COUNT(pt.photo_id) as photo_count
        FROM tags t
        JOIN photo_tags pt ON t.id = pt.tag_id
        GROUP BY t.id
        ORDER BY photo_count DESC
        LIMIT ?
      `).all(limit)
      
      return {
        success: true,
        data: tags
      }
    } catch (error) {
      console.error('获取热门标签失败:', error)
      return {
        success: false,
        error: '获取热门标签失败'
      }
    }
  })

  /**
   * 获取所有标签
   */
  ipcMain.handle('search:getAllTags', () => {
    try {
      const db = dbConnection.getConnection()
      
      const tags = db.prepare(`
        SELECT id, name, color
        FROM tags
        ORDER BY name ASC
      `).all()
      
      return {
        success: true,
        data: tags
      }
    } catch (error) {
      console.error('获取标签列表失败:', error)
      return {
        success: false,
        error: '获取标签列表失败'
      }
    }
  })

  /**
   * 获取相机品牌列表
   */
  ipcMain.handle('search:getCameraMakes', () => {
    try {
      const db = dbConnection.getConnection()
      
      const makes = db.prepare(`
        SELECT DISTINCT camera_make as value, COUNT(*) as count
        FROM photos
        WHERE camera_make IS NOT NULL
        ORDER BY count DESC
      `).all()
      
      return {
        success: true,
        data: makes
      }
    } catch (error) {
      console.error('获取相机品牌列表失败:', error)
      return {
        success: false,
        error: '获取相机品牌列表失败'
      }
    }
  })

  /**
   * 获取相机型号列表
   */
  ipcMain.handle('search:getCameraModels', (_, { make }) => {
    try {
      const db = dbConnection.getConnection()
      
      let query = `
        SELECT DISTINCT camera_model as value, COUNT(*) as count
        FROM photos
        WHERE camera_model IS NOT NULL
      `
      const params: any[] = []
      
      if (make) {
        query += ' AND camera_make = ?'
        params.push(make)
      }
      
      query += ' ORDER BY count DESC'
      
      const models = db.prepare(query).all(...params)
      
      return {
        success: true,
        data: models
      }
    } catch (error) {
      console.error('获取相机型号列表失败:', error)
      return {
        success: false,
        error: '获取相机型号列表失败'
      }
    }
  })
}